package itsm.isperp.framework.utils;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.module.entity.app.AppUploadFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.omg.CosNaming.NamingContextExtPackage.URLStringHelper;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.web.util.UriUtils;

/**
 * 文件工具
 * 
 * @version 1.0 生成通用文件名，读写文件
 * @version 1.1 增加文件拷贝
 */
public final class FileUtils {

	private static Log logger = LogFactory.getLog(FileUtils.class);

	private static String URL_SEPARATOR = "/";

	/**
	 * 
	 * @param fileType
	 * @param fileExt
	 *            文件后缀，如.txt，.rar等
	 * @return
	 */
	public static String generateFilepath(String fileType, String fileExt) {
		StringBuilder sb = new StringBuilder();

		if (org.apache.commons.lang3.StringUtils.isNotEmpty(fileType)) {
			sb.append(fileType).append(URL_SEPARATOR);
		}

		sb.append(DateUtils.DF_SSHORT.format(new Date())).append(URL_SEPARATOR)
				.append(HibernateUUIDGenerator.generate()).append(fileExt);

		return sb.toString();
	}

	/**
	 * 
	 * 
	 * 
	 * @param originalFilename
	 * @return
	 * 
	 */
	public static String generateFilename(String originalFilename) {

		SimpleDateFormat dirSdf = new SimpleDateFormat("yyyyMM");
		String filePre = dirSdf.format(new Date());

		String fileExt = getFileExtname(originalFilename);

		String filename = filePre + URL_SEPARATOR + HibernateUUIDGenerator.generate()
				+ fileExt;

		return filename;
	}

	/**
	 * 获取文件扩展名
	 * 
	 * @param originalFilename
	 * @return
	 */
	public static String getFileExtname(String originalFilename) {

		String fileExt = "";
		int lastIndex = originalFilename.lastIndexOf('.');
		// 取得文件的扩展名
		if (lastIndex != -1) {
			fileExt = originalFilename.substring(lastIndex);
		}

		return fileExt;
	}

	/**
	 * 写入文件
	 * 
	 * @param fileName
	 * @param writeFileName
	 */
	public static void writeFile(String fileName, String content) {
		FileOutputStream fileoutputstream;
		OutputStreamWriter outputstreamwriter;
		fileoutputstream = null;
		outputstreamwriter = null;
		try {
			File f = new File(fileName);
			if (!f.getParentFile().exists()) {
				f.getParentFile().mkdirs();

			}
			fileoutputstream = new FileOutputStream(f);
			outputstreamwriter = new OutputStreamWriter(fileoutputstream,
					"UTF-8");
			outputstreamwriter.write(content);

			if (outputstreamwriter != null)
				outputstreamwriter.close();
			if (fileoutputstream != null)
				fileoutputstream.close();
		} catch (Exception exception) {
			logger.error(exception.getMessage());
		}

	}

	public static String readFile(String fileName) throws IOException {
		InputStream xmlStream = new FileInputStream(fileName);

		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] data = new byte[4096];
		int count = -1;
		while ((count = xmlStream.read(data, 0, 4096)) != -1)
			outStream.write(data, 0, count);
		return new String(outStream.toByteArray(), "UTF-8");
	}

	// /**
	// * 根据文件名读取文件内容
	// *
	// * @param fileName
	// * 文件名
	// * @return 文件内容
	// */
	// public static String readFile(String fileName) {
	// StringBuffer stringbuffer = new StringBuffer();
	// try {
	// File file = new File(fileName);
	//
	// FileInputStream fileinputstream = new FileInputStream(file);
	// InputStreamReader inputstreamreader = new InputStreamReader(
	// fileinputstream, "UTF-8");
	// BufferedReader bufferedreader = new BufferedReader(
	// inputstreamreader);
	// String str;
	// while ((str = bufferedreader.readLine()) != null) {
	// stringbuffer.append(str);
	// stringbuffer.append("\r\n");
	// }
	// bufferedreader.close();
	// inputstreamreader.close();
	// fileinputstream.close();
	//
	// } catch (Exception exception) {
	// logger.error(exception.getMessage());
	// }
	// return stringbuffer.toString();
	// }

	/**
	 * 复制文件
	 * 
	 * 
	 * @param sourceFile
	 *            源文件
	 * @param targetFile
	 *            目标文件
	 * @throws IOException
	 * 
	 */
	public static boolean copyFile(File sourceFile, File targetFile)
			throws IOException {

		if (sourceFile.getCanonicalFile().equals(targetFile.getCanonicalFile())) {
			return false;
		}

		File pFile = targetFile.getParentFile();
		if (!pFile.exists()) {
			pFile.mkdirs();
		}

		int length = 2097152;
		FileInputStream in = new FileInputStream(sourceFile);
		FileOutputStream out = new FileOutputStream(targetFile);

		FileChannel inC = in.getChannel();
		FileChannel outC = out.getChannel();
		ByteBuffer b = null;
		while (true) {
			if (inC.position() == inC.size()) {
				inC.close();
				outC.close();
				return true;
			}
			if ((inC.size() - inC.position()) < length) {
				length = (int) (inC.size() - inC.position());
			} else
				length = 2097152;
			b = ByteBuffer.allocateDirect(length);
			inC.read(b);
			b.flip();
			outC.write(b);
			outC.force(false);
		}
	}

	/**
	 * 删除路径指定的文件或文件夹
	 * 
	 * @param filepath
	 * @throws IOException
	 */
	public static void delFileOrDir(String filepath) throws IOException {
		File f = new File(filepath);// 定义文件路径
		if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
			if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
				f.delete();
			} else {// 若有则把文件放进数组，并判断是否有下级目录
				File delFile[] = f.listFiles();
				int i = f.listFiles().length;
				for (int j = 0; j < i; j++) {
					if (delFile[j].isDirectory()) {
						delFileOrDir(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
					}
					// 删除文件
					delFile[j].delete();
				}
			}
		}
	}

	public static String getClassesPath() {
		String templatePath = Thread.currentThread().getContextClassLoader()
				.getResource("").toString();
		if (templatePath.startsWith("file:/")) {
			templatePath = templatePath.replaceFirst("file:/", "");
		}
		templatePath = templatePath.replace("/", File.separator);
		return templatePath;
	}

	public static String getFileRealPath(String path) {
		return ContextHolder.getApplicationPath() + "/" + path;
	}
}